package cn.buk.qms.web;

import cn.buk.common.JsonResult;
import cn.buk.common.dto.CommonDto;
import cn.buk.common.flight.dto.FlightInfoDto;
import cn.buk.common.util.DateUtil;
import cn.buk.tms.dto.AuthInfo;
import cn.buk.tms.dto.FlightOrderPassengerDto;
import cn.buk.tms.dto.FlightOrderStatusStat;
import cn.buk.tms.dto.ItineraryInfo;
import cn.buk.tms.entity.order.flight.FlightOrderPassenger;
import cn.buk.tms.entity.misc.OperationLog;
import cn.buk.tms.exception.BaseException;
import cn.buk.tms.sc.SearchFlightOrderCriteria;
import cn.buk.qms.service.FlightOrderService;
import cn.buk.tms.flight.dto.FlightCouponInfo;
import cn.buk.tms.flight.dto.FlightOfferPrice;
import cn.buk.tms.flight.dto.FlightRefundFee;
import cn.buk.tms.flight.dto.FlightSearchCriteria;
import cn.buk.tms.flight.dto.response.FlightOrderResponseDto;
import cn.buk.tms.flight.request.FlightOrderRequestDto;
import cn.buk.tms.flight.service.AutoTicketService;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import static org.apache.xmlgraphics.util.MimeConstants.MIME_PDF;

/**
 * @author yfdai
 *
 * 机票订单 控制器
 */
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

  private static final Logger logger = LogManager.getLogger(OrderController.class);

  @Autowired
  public OrderController(FlightOrderService flightOrderService,
                         AutoTicketService autoTicketService) {
    super();
    this.flightOrderService = flightOrderService;
    this.autoTicketService = autoTicketService;
  }


  private final FlightOrderService flightOrderService;

  private final AutoTicketService autoTicketService;

  /**
   * 1、创建机票订单
   */
  @PostMapping(value = "/flight/new", consumes = "application/json")
  public JsonResult createFlightOrder(HttpServletRequest request,
                                      @RequestBody FlightOrderRequestDto dto) {
    final int enterpriseId = getEnterpriseId(request);
    final String operator = getUsername(request);

    return flightOrderService.createFlightOrder(enterpriseId, operator, dto);
  }

  /**
   * 通过记录编码或编码内容直接生成机票订单, 方便只用短信发送的客户生成订单后发送短信
   */
  @PostMapping(value = "/flight/pnr")
  public JsonResult createFlightOrderByPnrDetail(HttpServletRequest request,
                                                 @RequestParam("pnrDetail") String pnrDetail) {
    final int enterpriseId = getEnterpriseId(request);
    final String operator = getUsername(request);

    return flightOrderService.createFlightOrderByPnrDetail(enterpriseId, operator, pnrDetail);
  }

  /**
   * 上传订单的乘机人资料
   */
  @PostMapping(value = "/flight/{orderId}/passengers/upload")
  public JsonResult uploadPassenger4FlightOrder(HttpServletRequest request,
                                      @PathVariable("orderId") int orderId,
                                                MultipartFile upfile
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    String fileName = getUserId(request) + "0" +  DateUtil.getCurDateTimeString("yyyyMMddHHmmss");

    String filePath = System.getProperty("java.io.tmpdir") +  File.separator + fileName;
    logger.info(filePath);
    File outputFile = new File(filePath);
    try {
      FileCopyUtils.copy(upfile.getBytes(), outputFile);
    } catch (IOException e) {
      e.printStackTrace();
      return JsonResult.createJsonResult(-1, "文件处理失败");
    }

    return flightOrderService.uploadPassenger4FlightOrder(enterpriseId, username, orderId, filePath);
  }

  /**
   * 校验航班价格
   * 使用NDC CZ api 进行价格校验
   */
  @PostMapping(value = "/flight/{orderId}/checkPrice")
  public FlightOfferPrice checkFlightOrderPrice(HttpServletRequest request,
                                                @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.checkFlightOrderPrice(enterpriseId, username, orderId);
  }

  /**
   * 查询可用的优惠券
   */
  @PostMapping(value = "/flight/{orderId}/coupons")
  public FlightCouponInfo searchCoupons(HttpServletRequest request,
                                        @PathVariable("orderId") int orderId
  ) {
    var authInfo = AuthInfo.createAuthInfo(getEnterpriseId(request), getUserId(request), getUsername(request));

    return flightOrderService.searchFlightOrderCoupons(authInfo, orderId);
  }

  @PostMapping(value = "/flight/{orderId}/confirmPrice")
  public JsonResult confirmFlightOrderPrice(HttpServletRequest request,
                                                @PathVariable("orderId") int orderId,
                                            @RequestParam("itemCodes[]") List<String> itemCodes,
                                            @RequestParam("shoppingResponseId") String shoppingResponseId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.confirmFlightOrderPrice(enterpriseId, username, orderId, shoppingResponseId, itemCodes);
  }

  /**
   * 同步外部订单状态
   */
  @PostMapping(value = "/flight/{orderId}/syncStatus")
  public JsonResult syncFlightOrderStatus(HttpServletRequest request,
                                            @PathVariable("orderId") int orderId
  ) throws BaseException {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.syncFlightOrderStatus(enterpriseId, username, orderId, 0);
  }

  /**
   * CZ NDC 支付
   */
  @PostMapping(value = "/flight/{orderId}/pay")
  public JsonResult payForFlightOrder(HttpServletRequest request,
                                          @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.payForFlightOrder(enterpriseId, username, orderId);
  }

  /**
   * CZ NDC 一键出票
   */
  @PostMapping(value = "/flight/{orderId}/issueTicket")
  public JsonResult issueFlightOrderTicket(HttpServletRequest request,
                                      @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return autoTicketService.issueFlightOrderTicket(enterpriseId, username, orderId);
  }

  /**
   * CZ NDC 查询退票费
   */
  @GetMapping(value = "/flight/{orderId}/refundFee")
  public FlightRefundFee queryOrderRefundFee(HttpServletRequest request,
                                             @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.queryOrderRefundFee(enterpriseId, username, orderId);
  }

  /**
   * CZ NDC 改签航班查询
   */
  @PostMapping(value = "/flight/{orderId}/changeQuery", consumes = "application/json")
  public CommonDto<FlightInfoDto> queryOrderChange(HttpServletRequest request,
                                                   @PathVariable("orderId") int orderId,
                                                   @RequestBody List<FlightSearchCriteria> flightSearchCriterias
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.queryOrderChange(enterpriseId, username, orderId, flightSearchCriterias);
  }


  /**
   * 2、申请开票
   */
  @PostMapping(value = "/flight/{orderId}/submit")
  public JsonResult submitFlightOrder(HttpServletRequest request,
                                      @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.submitFlightOrder(enterpriseId, username, orderId);
  }

  /**
   * 3、认领开票（我来开票)
   */
  @PostMapping(value = "/flight/{orderId}/toticket")
  public JsonResult toTicketFlightOrder(HttpServletRequest request,
                                        @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.toTicketFlightOrder(enterpriseId, username, orderId);
  }

  /**
   * 3、取消认领开票（我来开票)
   */
  @PostMapping(value = "/flight/{orderId}/cancelClaim")
  public JsonResult cancelClaimFlightOrder(HttpServletRequest request,
                                        @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.cancelClaimFlightOrder(enterpriseId, username, orderId);
  }

  /**
   * 4、回填机票订单的票号（完成开票）
   */
  @PostMapping(value = "/flight/{orderId}/ticket", consumes = "application/json")
  public JsonResult updateFlightOrderTicketNo(HttpServletRequest request,
                                              @PathVariable("orderId") int orderId,
                                              @RequestBody List<FlightOrderPassenger> passengers
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
            .updateFlightOrderTicketNo(enterpriseId, username, orderId, passengers);
  }

  /**
   * 5、完成订单（关闭订单）
   */
  @PostMapping(value = "/flight/{orderId}/finish")
  public JsonResult finishFlightOrder(HttpServletRequest request,
                                      @PathVariable("orderId") int orderId,
                                      @RequestParam(value = "etdzDate", required = false) Date etdzDate
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.finishFlightOrder(enterpriseId, username, orderId, etdzDate);
  }

  /**
   * 查找机票订单
   */
  @RequestMapping("/flights")
  public CommonDto<FlightOrderResponseDto> searchFlightOrders(HttpServletRequest request,
      @ModelAttribute("sc") SearchFlightOrderCriteria sc
  ) {
    return flightOrderService.searchFlightOrders2(getEnterpriseId(request), getUserId(request), getUsername(request), sc);
  }

  /**
   * 查找需要送票的机票订单, 有派送日期的才显示，不区分订单状态
   */
  @RequestMapping("/flights/delivery")
  public CommonDto<FlightOrderResponseDto> searchNeedDeliveryFlightOrders(HttpServletRequest request,
      @ModelAttribute("sc") SearchFlightOrderCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    // 搜索派送单
    sc.setSearchType(SearchFlightOrderCriteria.SEARCH_TO_DELIVERY);
    // 国内国际
    sc.setIntlTicket(-1);
    if (sc.getBeginDate() == null && sc.getEndDate() == null) {
      sc.setBeginDate(DateUtil.getYesterday());
    }

    List<FlightOrderResponseDto> datas = flightOrderService.searchNeedDeliveryFlightOrders(enterpriseId, userId, sc);

    CommonDto<FlightOrderResponseDto> commonDto = new CommonDto<>();
    commonDto.setDataList(datas);
    commonDto.setPage(sc.getPage());

    return commonDto;
  }

  /**
   * 查找需要打印的机票订单
   */
  @RequestMapping("/flights/print")
  public CommonDto<FlightOrderResponseDto> searchNeedPrintFlightOrders(HttpServletRequest request,
      @ModelAttribute("sc") SearchFlightOrderCriteria sc) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    //* 1 - 搜索待打印的（日期使用出票日期）
    sc.setSearchType(SearchFlightOrderCriteria.SEARCH_TO_PRINT);

    List<FlightOrderResponseDto> datas = flightOrderService.searchNeedDeliveryFlightOrders(enterpriseId, userId, sc);

    CommonDto<FlightOrderResponseDto> commonDto = new CommonDto<>();
    commonDto.setDataList(datas);
    commonDto.setPage(sc.getPage());

    return commonDto;
  }

  /**
   * 获取机票订单详情
   */
  @RequestMapping("/flight/{id}")
  public FlightOrderResponseDto getFlightOrderDetail(HttpServletRequest request,
                                                     @PathVariable("id") int id) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    return flightOrderService.getFlightOrderDetail(enterpriseId, userId, id);
  }

  /**
   * 获取机票订单详情
   */
  @RequestMapping("/flight/orderNo/{orderNo}")
  public FlightOrderResponseDto getFlightOrderDetailByOrderNo(HttpServletRequest request,
      @PathVariable("orderNo") String orderNo
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final int userId = getUserId(request);

    return flightOrderService.getFlightOrderDetailByOrderNo(enterpriseId, userId, orderNo);
  }

  /**
   * 获取机票订单操作记录
   */
  @RequestMapping("/flight/{orderId}/history")
  public List<OperationLog> searchFlightOrderHistory(HttpServletRequest request,
      @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);

    return flightOrderService.searchFlightOrderHistory(enterpriseId, orderId);
  }

  /**
   * 修改机票订单价格
   */
  @PostMapping(value = "/flight/{id}/price", consumes = "application/json")
  public JsonResult updateFlightOrderPrice(HttpServletRequest request,
      @PathVariable("id") int id,
      @RequestBody FlightOrderRequestDto dto
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.updateFlightOrderPrice(enterpriseId, username, id, dto);
  }


  /**
   * 修改机票订单的乘机人信息
   */
  @PostMapping(value = "/flight/{orderId}/passenger")
  public JsonResult updateFlightOrderPsg(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("id") int psgId,
      @RequestParam("name") String psgName,
      @RequestParam("idNo") String psgIdNo,
      @RequestParam("ffpNo") String psgFfpNo,
      @RequestParam(value = "mobile", required = false, defaultValue = "") String psgMobile,
      @RequestParam(value = "birthday", required = false) Date birthday,
      @RequestParam(value = "psgType", required = false, defaultValue = "-1") int psgType,
      @RequestParam(value = "gender", required = false, defaultValue = "-1") int gender
  ) {
    var authInfo = new AuthInfo(getEnterpriseId(request), getUserId(request), getUsername(request));
    var psgDto = new FlightOrderPassengerDto(orderId, psgId, psgName);
    psgDto.setIdNo(psgIdNo);
    psgDto.setFfpNo(psgFfpNo);
    psgDto.setMobile(psgMobile);
    psgDto.setBirthday(birthday);
    psgDto.setPsgType(psgType);
    psgDto.setGender(gender);

    return flightOrderService.updateFlightOrderPassenger(authInfo, psgDto);
  }

  /**
   * 修改机票订单的备注
   */
  @PostMapping(value = "/flight/{orderId}/remark")
  public JsonResult updateFlightOrderRemark(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("remark") String remark
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.updateFlightOrderProperty(enterpriseId, username, orderId, "remark", remark);
  }

  /**
   * 修改机票订单的编码
   */
  @PostMapping(value = "/flight/{orderId}/pnr")
  public JsonResult updateFlightOrderPnr(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("pnrNo") String pnrNo) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.updateFlightOrderPnr(enterpriseId, username, orderId, pnrNo);
  }

  /**
   * 修改机票订单的用到的大客户代码
   */
  @PostMapping(value = "/flight/{orderId}/keyCustomerNo")
  public JsonResult updateFlightOrderKeyCustomerNo(HttpServletRequest request,
                                         @PathVariable("orderId") int orderId,
                                         @RequestParam("keyCustomerNo") String keyCustomerNo) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.updateFlightOrderKeyCustomerNo(enterpriseId, username, orderId, keyCustomerNo);
  }

  /**
   * 修改机票订单的某个属性
   */
  @PostMapping(value = "/flight/{orderId}/property")
  public JsonResult updateFlightOrderProperty(HttpServletRequest request,
                                                   @PathVariable("orderId") int orderId,
                                                   @RequestParam("name") String propertyName,
                                                   @RequestParam("value") String propertyValue) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.updateFlightOrderProperty(enterpriseId, username, orderId, propertyName, propertyValue);
  }

  /**
   * 增加机票订单的打印次数
   */
  @PostMapping(value = "/flight/{orderId}/print")
  public JsonResult printFlightOrder(HttpServletRequest request,
      @PathVariable("orderId") int orderId) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.incFlightOrderPrintCount(enterpriseId, username, orderId);
  }

  /**
   * 修改机票订单的供应商
   *
   * @param request HttpServletRequest
   * @param orderId 订单id
   * @param supplierId 供应商id
   * @param paymentMethodId 支出方式id
   * @param autoTicketing 是否自动出票
   * @param price 自动出票时选择的价格
   */
  @PostMapping(value = "/flight/{orderId}/supplier")
  public JsonResult updateFlightOrderSupplier(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("supplierId") int supplierId,
      @RequestParam(value = "paymentMethodId", defaultValue = "0") int paymentMethodId,
      @RequestParam(value = "autoTicketing", defaultValue = "0") int autoTicketing,
      @RequestParam(value = "price", defaultValue = "0") int price
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .updateFlightOrderTicketOptions(enterpriseId, username, orderId, supplierId,
            paymentMethodId, autoTicketing, price);
  }

  /**
   * 修改机票订单的供应商类型
   */
  @PostMapping(value = "/flight/{orderId}/supplierType")
  public JsonResult updateFlightOrderSupplierType(HttpServletRequest request,
                                              @PathVariable("orderId") int orderId,
                                              @RequestParam("supplierType") int supplierType
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.updateFlightOrderSupplierType(enterpriseId, username, orderId, supplierType);
  }

  /**
   * 修改机票订单的客户
   */
  @PostMapping(value = "/flight/{orderId}/customer")
  public JsonResult updateFlightOrderCustomer(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("customerId") int customerId,
      @RequestParam("costCenter") String costCenter) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);
    return flightOrderService
        .updateFlightOrderCustomer(enterpriseId, username, orderId, customerId, costCenter);
  }

  /**
   * 修改机票订单的国际国内属性
   */
  @PostMapping(value = "/flight/{orderId}/intlTicket")
  public JsonResult updateFlightOrderCustomer(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("intlTicket") int intlTicket) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);
    return flightOrderService
        .updateFlightOrderIntlTicket(enterpriseId, username, orderId, intlTicket);
  }

  /**
   * 修改机票订单的支付方式
   */
  @PostMapping(value = "/flight/{orderId}/paymentMethod")
  public JsonResult updateFlightOrderPaymentMethod(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("paymentMethodId") int paymentMethodId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .updateFlightOrderPaymentMethod(enterpriseId, username, orderId, paymentMethodId);
  }


  /**
   * 取消关联(删除机票订单中的指定额外服务)
   */
  @PostMapping(value = "/flight/{orderId}/extra/{extraId}/delete")
  public JsonResult delFlightOrderExtra(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @PathVariable("extraId") int extraId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.delFlightOrderExtra(enterpriseId, username, orderId, extraId);
  }

  /**
   * 申请取消/取消订单
   *
   * @param orderId 订单id
   * @param reasonCode 原因代码
   * @param reasonDesc 原因描述
   */
  @PostMapping(value = "/flight/{orderId}/status/canceled")
  public JsonResult cancelFlightOrder(HttpServletRequest request,
                                      @PathVariable("orderId") int orderId,
                                      @RequestParam(name = "reasonCode", defaultValue = "0") int reasonCode,
                                      @RequestParam(name = "reasonDesc") String reasonDesc) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.cancelFlightOrder(enterpriseId, username, orderId, reasonCode, reasonDesc);
  }

  /**
   * 审批通过
   */
  @PostMapping(value = "/flight/{orderId}/approved")
  public JsonResult approveFlightOrder(HttpServletRequest request,
      @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.approveFlightOrder(enterpriseId, username, orderId);
  }

  /**
   * 同意 订单取消请求
   */
  @PostMapping(value = "/flight/{orderId}/agreeCancelRequest")
  public JsonResult agreeFlightOrderCancelRequest(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("requestId") int requestId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .agreeFlightOrderCancelRequest(enterpriseId, username, orderId, requestId);
  }

  /**
   * 拒绝 订单取消请求
   */
  @PostMapping(value = "/flight/{orderId}/denyCancelRequest")
  public JsonResult denyFlightOrderCancelRequest(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("requestId") int requestId,
      @RequestParam(value = "reasonCode", defaultValue = "0") int reasonCode,
      @RequestParam("reasonDesc") String reasonDesc
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .denyFlightOrderCancelRequest(enterpriseId, username, orderId, requestId, reasonCode,
            reasonDesc);
  }

  /**
   * 行程单已邮寄
   */
  @PostMapping(value = "/flight/{orderId}/delivery/finished")
  public JsonResult finishFlightOrderItineraryDelivery(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("remark") String remark
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .finishFlightOrderItineraryDelivery(enterpriseId, username, orderId, remark);
  }


  /**
   * 机票订单发送短信, 允许使用客户端发送来的短信内容
   */
  @PostMapping(value = "/flight/{id}/sms")
  public JsonResult sendFlightOrderSms(HttpServletRequest request,
      @PathVariable("id") int orderId,
      @RequestParam(value = "psgId", defaultValue = "0") int psgId,
      @RequestParam(value = "mobileNo", defaultValue = "") String mobileNo,
      @RequestParam(value = "smsContent", required = false) String smsContent,
      @RequestParam(value = "smsFormat", defaultValue = "0") int smsFormat // 短信格式
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .sendFlightOrderSms(enterpriseId, username, orderId, psgId, mobileNo, smsContent,
            smsFormat);
  }

  /**
   * 获取机票订单发送短信的内容
   */
  @PostMapping(value = "/flight/{id}/smsContent")
  public JsonResult getFlightOrderSmsContent(HttpServletRequest request,
      @PathVariable("id") int orderId,
      @RequestParam(value = "psgId", defaultValue = "0") int psgId,
      @RequestParam(value = "smsFormat", defaultValue = "0") int smsFormat // 短信格式
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .getFlightOrderSmsContent(enterpriseId, username, orderId, psgId, smsFormat);
  }

  /**
   * 发预定成功短信
   */
  @PostMapping(value = "/flight/{orderId}/sendApprovalSms")
  public JsonResult sendFlightOrderApprovalSms(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam(value = "mobileNo", defaultValue = "") String mobileNo,
      @RequestParam(value = "smsContent", required = false) String smsContent
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .sendFlightOrderApprovalSms(enterpriseId, username, orderId, mobileNo, smsContent);
  }

  /**
   * 获取订单要求审批的短信内容
   */
  @PostMapping(value = "/flight/{orderId}/approvalSmsContent")
  public JsonResult getFlightOrderApprovalSmsContent(HttpServletRequest request,
      @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.getFlightOrderApprovalSmsContent(enterpriseId, username, orderId);
  }


  /**
   * 统计机票订单、改签单、退费单的订单状态数量，便于为业务操作做提醒
   */
  @PostMapping(value = "/flight/statStatus")
  public FlightOrderStatusStat statFlightMiscOrderStatus(HttpServletRequest request) {
    final int enterpriseId = getEnterpriseId(request);
    return flightOrderService.statFlightMiscOrderStatus(enterpriseId);
  }

  /**
   * 修改机票订单的派送日期
   */
  @PostMapping(value = "/flight/{orderId}/deliveryDate")
  public JsonResult updateFlightOrderDeliveryDate(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("deliveryDate") Date deliveryDate
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService
        .updateFlightOrderDeliveryDate(enterpriseId, username, orderId, deliveryDate);
  }

  /**
   * 修改机票订单的出票员
   */
  @PostMapping(value = "/flight/{orderId}/ticketer")
  public JsonResult updateFlightOrderTicketer(HttpServletRequest request,
      @PathVariable("orderId") int orderId,
      @RequestParam("ticketer") String ticketer
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.updateFlightOrderTicketer(enterpriseId, username, orderId, ticketer);
  }

  /**
   * 修改机票订单通知的确认状态
   */
  @PostMapping(value = "/flight/{orderId}/noticeConfirmed")
  public JsonResult confirmFlightOrderNotice(HttpServletRequest request,
                                              @PathVariable("orderId") int orderId
  ) {
    final int enterpriseId = getEnterpriseId(request);
    final String username = getUsername(request);

    return flightOrderService.confirmFlightOrderNotice(enterpriseId, username, orderId);
  }

  private final TransformerFactory tFactory = TransformerFactory.newInstance();

  @RequestMapping(value = "/flight/{orderId}/itinerary")
  public void downloadFlightOrderItinerary(HttpServletRequest request,
      HttpServletResponse response,
      @PathVariable("orderId") int orderId) {
    try {
      logger.info("flight order to itinerary: {}.", orderId);
      response.setContentType("application/pdf");

      String filePath0 = Thread.currentThread().getContextClassLoader().getResource("fop.xml")
          .getPath();
      FopFactory fopFactory = FopFactory.newInstance(new File(filePath0));

      String baseUri = fopFactory.getFontManager().getResourceResolver().getBaseURI().toString();

      logger.info("baseUri: {}.", baseUri);

      // Construct fop with desired output format
      Fop fop = fopFactory.newFop(MIME_PDF, response.getOutputStream());

      // Setup XSLT
      String xsltFilePath = Thread.currentThread().getContextClassLoader()
          .getResource("xml/xslt/itinerary2fo.xsl").getPath();
      File xslt = new File(xsltFilePath);
      Transformer transformer = tFactory.newTransformer(new StreamSource(xslt));

      // Setup input for XSLT transformation
      ItineraryInfo itineraryInfo = flightOrderService
          .createItineraryByFlightOrder(getEnterpriseId(request), orderId);
      Source src = itineraryInfo.getSourceForItinerary();

      // Resulting SAX events (the generated FO) must be piped through to FOP
      Result res = new SAXResult(fop.getDefaultHandler());

      // Start XSLT transformation and FOP processing
      transformer.transform(src, res);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }




}
